package com.wowangz.cms.syscore.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.jpush.pojo.Jpush;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.SqlSessionContainer;
import com.wowangz.cms.syscore.utils.EncryptUtil;
import com.wowangz.cms.syscore.utils.SystemConfig;
import com.wowangz.cms.systemmanage.databaseresource.pojo.DatabaseResource;
import com.wowangz.cms.systemmanage.databaseresource.service.DatabaseBindingService;
import com.wowangz.cms.systemmanage.parameter.pojo.Parameter;

/**
 * 统一定义公用字段及方法的service基类.
 * 
 * @author issuser
 *
 */
@SuppressWarnings("rawtypes")
public class BaseService {
	
	//add by yoyo 获取配置的运行自动任务服务名
	private static SystemConfig systemConfig=new SystemConfig("autoTaskRunServer");
	private static Map systemConfigMap = systemConfig.getKeyValueMap();

	/**
	 * 获得request对象
	 * 
	 * @return
	 */
	public HttpServletRequest getHttpRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		return request;
	}

	public SqlSession getSqlSession() {
		SqlSessionContainer sessionContainer = new SqlSessionContainer();
		SqlSession sqlSession = (SqlSession) sessionContainer.getSqlSession();
		return sqlSession;
	}

	public Connection getConnection(Long storeid) throws SQLException {

		Connection conn = null;
		DatabaseBindingService databaseBindingService = (DatabaseBindingService) IssTransactionContainer
				.getInstance(DatabaseBindingService.class, true);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("storeid", storeid);
		map.put("statusid", SysConstant.RecordStatus.VALID);
		map.put("state", SysConstant.CommonApproveStatus.OK);
		DatabaseResource databaseResource = databaseBindingService
				.queryDatabaseBinding(map);
		String ip = databaseResource.getIp();
		String port = String.valueOf(databaseResource.getPort());
		String dbname = databaseResource.getDbname();
		String driver = "com.mysql.jdbc.Driver"; // 获取mysql数据库的驱动类
		String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbname; // 连接数据库（kucun是数据库名）
		String name = databaseResource.getUsername();// 连接mysql的用户名
		String pwd = databaseResource.getPassword();// 连接mysql的密码

		try {
			Class.forName(driver);
			DriverManager.setLoginTimeout(5);
			conn = DriverManager.getConnection(url, name, pwd);// 获取连接对象
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public void sendTransDataToMq(String json,String queue) {

		ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD, systemConfigMap.get("mq_queue").toString());
		javax.jms.Connection connection = null;
		Session session = null;
		try {
			long starttime = System.currentTimeMillis();
			connection = factory.createConnection();
			connection.start();
			session = connection.createSession(Boolean.FALSE,
					Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(queue);
			MessageProducer producer = session.createProducer(destination);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			ObjectMessage message = session.createObjectMessage(json);
			producer.send(message);
			long endtime = System.currentTimeMillis();
			System.out.println(endtime - starttime);

		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				try {
					session.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void sendEmailData(Map<String, Object> messageMap) throws Exception {
		EncryptUtil des1 = new EncryptUtil();// 使用默认密钥
		String content = messageMap.get("content").toString();
		content = EncryptUtil.toUnicode(content);
		messageMap.put("content", des1.encrypt(content));
		sendTransDataToMq(new Gson().toJson(messageMap), SysConstant.MQQUEUE.MQ_SENDEMAIL);
	}
	
	/**
	 * 设置推送消息
	 * @param messageMap
	 * @throws Exception
	 */
	public void sendjJpushData(Jpush jpush) throws Exception {
		EncryptUtil des1 = new EncryptUtil();// 使用默认密钥
		String jpushStr = des1.encrypt(EncryptUtil.toUnicode(new Gson().toJson(jpush)));
		sendTransDataToMq(jpushStr, SysConstant.MQQUEUE.MQ_JPUSH);
	}

	public Map getSysparameterValueByCode(String code) throws Exception{
		Map <String,String> map=new HashMap<String,String>();
		List<Parameter> list=this.getSqlSession().selectList("Parameter.queryParameter",code);
		for (Parameter parameter : list) {
			String parametercode=parameter.getCode();
			String value = parameter.getValue();
			map.put(parametercode, value);
		}
		return map;
	}
}
